package com.cxs.idldemo.slice;

import com.cxs.idldemo.*;
import com.cxs.idldemo.utils.DeviceUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.ElementName;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

public class MainAbilitySlice extends AbilitySlice {

    IRemoteAgent proxy;

    IAbilityConnection connection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            proxy = RemoteAgentStub.asInterface(iRemoteObject);
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            proxy = null;
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        findComponentById(ResourceTable.Id_btn_connect)
                .setClickedListener(c -> connectServie());

        findComponentById(ResourceTable.Id_btn_plus)
                .setClickedListener(c -> plus());

    }

    private void connectServie() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(DeviceUtil.getDeviceId())
                .withBundleName(getBundleName())
                .withAbilityName(ServiceAbility.class.getName())
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        intent.setOperation(operation);

        connectAbility(intent, connection);
    }

    private void plus() {
        try {
            int plus = proxy.plus(345, 653);
            System.out.println("" + plus);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
